package xyz.yq56.easytool.utils.json;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import xyz.yq56.easytool.factory.ObjectMapperFactory;
import xyz.yq56.easytool.utils.log.LogUtil;
import xyz.yq56.easytool.utils.nvll.NullUtil;
import xyz.yq56.easytool.utils.string.TextUtils;

/**
 * @author yi qiang
 * @date 2021/9/24 2:00
 */
public class JsonUtils {

    private JsonUtils() {
    }

    public static <T> T toObject(String str, Class<T> t) {
        try {
            ObjectMapper mapper = ObjectMapperFactory.get();
            return mapper.readValue(str, t);
        } catch (JsonProcessingException e) {
            LogUtil.error("Json反序列化失败", e, null);
        }
        return null;
    }

    public static String toJson(Object obj) {
        try {
            ObjectMapper mapper = ObjectMapperFactory.get();
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            LogUtil.error("Json序列化失败", e, null);
        }
        return null;
    }

    public static String toPrettyJson(Object obj) {
        try {
            ObjectMapper mapper = ObjectMapperFactory.get();
            return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            LogUtil.error("Json序列化失败", e, null);
        }
        return null;
    }

    public static <T> List<T> toList(String str) {
        try {
            ObjectMapper mapper = ObjectMapperFactory.get();
            return mapper.readValue(str, new TypeReference<List<T>>() {
            });
        } catch (JsonProcessingException e) {
            LogUtil.error("Json反序列化失败", e, null);
        }
        return Collections.emptyList();
    }

    /**
     * 普通数组型Json转化为CSV文件
     */
    public static void toCsv(String json, String fieldName) {
        List<HashMap<String, Object>> mapList = toList(NullUtil.emptyIfNull(json));
        List<String> headers = new ArrayList<>();
        List<String> columnList = new ArrayList<>();
        for (HashMap<String, Object> map : mapList) {
            StringBuilder sb = new StringBuilder();
            map.forEach((key, value) -> {
                //header如果不包含key,则添加进header
                if (!headers.contains(key)) {
                    headers.add(key);
                }
                //行数据
                for (String header : headers) {
                    if (key.equals(header)) {
                        sb.append(value).append(",");
                    }
                }
            });
            if (sb.toString().endsWith(",")) {
                columnList.add(TextUtils.removeLastChar(sb.toString()));
            }
        }

        List<String> totalColumnList = new ArrayList<>();
        totalColumnList.add(TextUtils.join(headers, ","));
        totalColumnList.addAll(columnList);

        try (BufferedWriter writer = new BufferedWriter(new FileWriter(fieldName))) {
            for (String column : totalColumnList) {
                writer.write(column);
                writer.newLine();
                writer.flush();
            }
        } catch (Exception e) {
            LogUtil.error("ToCSV", e, null);
        }

    }

}
